{% extends 'base.html' %}

{% block title %}智能问答 | Tiny QA{% endblock %}

{% block content %}
<div class="container mt-5">
    <h2 class="mb-4">智能问答</h2>
    <form id="qa-form" class="mb-3">
        <div class="input-group">
            <input type="text" class="form-control" id="question" placeholder="请输入您的问题..." required>
            <button class="btn btn-primary" type="submit">提问</button>
        </div>
    </form>
    
    <!-- 问答结果区域 -->
    <div id="qa-result" class="d-none">
        <div class="card mb-3">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="bi bi-chat-dots"></i> AI回答
                </h5>
            </div>
            <div class="card-body">
                <div id="think-block" class="d-none"></div>
                <div id="answer-text" class="answer-content"></div>
            </div>
        </div>
        <!-- 来源信息 -->
        <div id="sources-section" class="d-none">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">参考来源</h5>
                </div>
                <div class="card-body">
                    <div id="sources-list"></div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 加载状态 -->
    <div id="loading" class="text-center d-none">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">正在思考...</span>
        </div>
        <p class="mt-2">正在分析文档，请稍候...</p>
    </div>
    
    <!-- 错误信息 -->
    <div id="error-message" class="alert alert-danger d-none"></div>
</div>

<!-- 引入marked.js -->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

<script>
// 配置marked.js
marked.setOptions({
    breaks: true,  // 支持换行
    gfm: true,     // 支持GitHub风格Markdown
    sanitize: false, // 允许HTML标签
    smartLists: true, // 智能列表
    smartypants: true // 智能标点
});
</script>

<style>
.answer-content {
    line-height: 1.7;
    color: #333;
    font-size: 1.08rem;
    word-wrap: break-word;
    overflow-wrap: break-word;
}

/* 思考过程卡片 */
#think-block {
    background: #f0f4f8;
    border-left: 5px solid #5dade2;
    margin-bottom: 1.5rem;
    padding: 1rem 1.5rem;
    border-radius: 0.5rem;
    box-shadow: 0 2px 8px rgba(90,173,226,0.08);
}
#think-block .think-title {
    font-size: 1rem;
    color: #2980b9;
    font-weight: bold;
    margin-bottom: 0.5rem;
    letter-spacing: 1px;
}
#think-block .think-body {
    font-size: 0.97em;
    color: #666;
    font-style: italic;
    line-height: 1.7;
}

.answer-content h1, .answer-content h2, .answer-content h3, 
.answer-content h4, .answer-content h5, .answer-content h6 {
    color: #2c3e50;
    margin-top: 1.5rem;
    margin-bottom: 0.75rem;
    font-weight: 600;
}
.answer-content h1 { font-size: 1.8rem; border-bottom: 2px solid #3498db; padding-bottom: 0.5rem; }
.answer-content h2 { font-size: 1.5rem; border-bottom: 1px solid #ecf0f1; padding-bottom: 0.3rem; }
.answer-content h3 { font-size: 1.3rem; color: #34495e; }
.answer-content h4 { font-size: 1.1rem; color: #7f8c8d; }
.answer-content p {
    margin-bottom: 1rem;
    text-align: justify;
}
.answer-content ul, .answer-content ol {
    margin-bottom: 1rem;
    padding-left: 1.5rem;
}
.answer-content li {
    margin-bottom: 0.5rem;
    line-height: 1.5;
}
.answer-content strong, .answer-content b {
    color: #e74c3c;
    font-weight: 600;
}
.answer-content em, .answer-content i {
    color: #27ae60;
    font-style: italic;
}
.answer-content blockquote {
    border-left: 4px solid #3498db;
    padding-left: 1rem;
    margin: 1rem 0;
    background-color: #f8f9fa;
    padding: 1rem;
    border-radius: 0.25rem;
    font-style: italic;
    color: #555;
}
.answer-content code {
    background-color: #f1f2f6;
    padding: 0.2rem 0.4rem;
    border-radius: 0.25rem;
    font-family: 'Courier New', monospace;
    color: #e74c3c;
}
.answer-content pre {
    background-color: #2c3e50;
    color: #ecf0f1;
    padding: 1rem;
    border-radius: 0.5rem;
    overflow-x: auto;
    margin: 1rem 0;
}
.answer-content table {
    width: 100%;
    border-collapse: collapse;
    margin: 1rem 0;
    background-color: white;
    border-radius: 0.5rem;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.answer-content th, .answer-content td {
    padding: 0.75rem;
    text-align: left;
    border-bottom: 1px solid #ecf0f1;
}
.answer-content th {
    background-color: #3498db;
    color: white;
    font-weight: 600;
}
.answer-content tr:nth-child(even) {
    background-color: #f8f9fa;
}
.answer-content tr:hover {
    background-color: #e3f2fd;
}

/* 代码高亮 */
.answer-content pre code {
    background: none;
    padding: 0;
    color: inherit;
}

/* 行内代码 */
.answer-content code:not(pre code) {
    background-color: #f1f2f6;
    padding: 0.2rem 0.4rem;
    border-radius: 0.25rem;
    font-family: 'Courier New', monospace;
    color: #e74c3c;
    font-size: 0.9em;
}

/* 链接样式 */
.answer-content a {
    color: #3498db;
    text-decoration: none;
}

.answer-content a:hover {
    text-decoration: underline;
}

/* 水平分割线 */
.answer-content hr {
    border: none;
    border-top: 2px solid #ecf0f1;
    margin: 2rem 0;
}

/* 图片样式 */
.answer-content img {
    max-width: 100%;
    height: auto;
    border-radius: 0.5rem;
    margin: 1rem 0;
}

/* 任务列表 */
.answer-content input[type="checkbox"] {
    margin-right: 0.5rem;
}

/* 数学公式支持 */
.answer-content .math {
    font-family: 'Times New Roman', serif;
    font-style: italic;
}
</style>

<script>
const form = document.getElementById('qa-form');
const questionInput = document.getElementById('question');
const qaResult = document.getElementById('qa-result');
const loading = document.getElementById('loading');
const errorMessage = document.getElementById('error-message');
const questionText = document.getElementById('question-text');
const answerText = document.getElementById('answer-text');
const thinkBlock = document.getElementById('think-block');
const sourcesSection = document.getElementById('sources-section');
const sourcesList = document.getElementById('sources-list');

form.addEventListener('submit', async function(e) {
    e.preventDefault();
    const question = questionInput.value.trim();
    if (!question) return;
    
    // 显示加载状态
    loading.classList.remove('d-none');
    qaResult.classList.add('d-none');
    errorMessage.classList.add('d-none');
    thinkBlock.classList.add('d-none');
    answerText.innerHTML = '';
    
    try {
        const resp = await fetch('/api/qa', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ question })
        });
        const data = await resp.json();
        if (resp.ok && data.answer) {
            // 分离思考过程和正式回答
            let answer = data.answer;
            let thinkHtml = '';
            let mainHtml = answer;
            // 提取<think>内容
            const thinkMatch = answer.match(/<think>([\s\S]*?)<\/think>/);
            if (thinkMatch) {
                try {
                    thinkHtml = `<div class="think-title">💡 思考过程</div><div class="think-body">${marked.parse(thinkMatch[1])}</div>`;
                } catch (error) {
                    console.warn('思考过程Markdown解析失败，使用原始文本:', error);
                    thinkHtml = `<div class="think-title">💡 思考过程</div><div class="think-body">${thinkMatch[1].replace(/\n/g, '<br>')}</div>`;
                }
                thinkBlock.innerHTML = thinkHtml;
                thinkBlock.classList.remove('d-none');
                mainHtml = answer.replace(thinkMatch[0], '');
            } else {
                thinkBlock.classList.add('d-none');
                thinkBlock.innerHTML = '';
            }
            // 渲染正式回答Markdown
            try {
                answerText.innerHTML = marked.parse(mainHtml);
            } catch (error) {
                console.warn('Markdown解析失败，使用原始文本:', error);
                answerText.innerHTML = mainHtml.replace(/\n/g, '<br>');
            }
            qaResult.classList.remove('d-none');
            // 显示来源信息
            if (data.sources && data.sources.length > 0) {
                let sourcesHtml = '';
                data.sources.forEach((source, index) => {
                    sourcesHtml += `
                        <div class="mb-3 p-3 border rounded">
                            <h6 class="mb-2">
                                <i class="bi bi-file-text"></i> 
                                ${source.file_name}
                                <span class="badge bg-secondary ms-2">相似度: ${source.similarity}</span>
                            </h6>
                            <p class="mb-0 text-muted small">${source.content}</p>
                        </div>
                    `;
                });
                sourcesList.innerHTML = sourcesHtml;
                sourcesSection.classList.remove('d-none');
            } else {
                sourcesSection.classList.add('d-none');
            }
        } else {
            errorMessage.textContent = data.error || '获取答案失败';
            errorMessage.classList.remove('d-none');
        }
    } catch (err) {
        errorMessage.textContent = '网络或服务器错误: ' + err.message;
        errorMessage.classList.remove('d-none');
    } finally {
        loading.classList.add('d-none');
    }
});
</script>
{% endblock %} 